package encryption;

import Navi_run.params;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.Pairing;
import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.HashMap;

import static encryption.RSA.generateRsaKeyPair;

public class demoforshort {
    public static Field G1;
    public static Field G2;
    public static Pairing pairing;

    public static BigInteger gsk_x;
    public static BigInteger gsk_y;
    public static Element gpk_g;
    public static Element gpk_h;
    public static Element gpk_X;
    public static Element gpk_Y;

    public static void  SetUp() {
        params.pairing = pairing = PairingFactory.getPairing("./config/a.properties");
        params.G1 = G1 = pairing.getG1();
        params.G2 = G2 = pairing.getG2();
    }

    //TA获取组公私钥
    public static void generateGroupKeyPair() {
        try {
            //采用SHA1PRNG的随机算法生成随机数 SHA1PRNG的效率比NativePRNG的效率高
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            //获取组私钥gsk (a,b)来自于正整数群
            gsk_x =new BigInteger(256,secureRandom);
            gsk_y =new BigInteger(256,secureRandom);
            //System.out.println("gsk_x:" + gsk_x + "\ngsk_y:" + gsk_y);
            //获取组公钥gpk
            gpk_g = G2.newRandomElement().getImmutable();
            gpk_X = gpk_g.pow(gsk_x).getImmutable();
            gpk_Y = gpk_g.pow(gsk_y).getImmutable();
            gpk_h = G1.newRandomElement().getImmutable();
            // 获取RSA公私钥
            params.RSAkeyMap = generateRsaKeyPair();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    public static HashMap<String,Element> sign(BigInteger x, BigInteger y, String message){
        BigInteger m = new BigInteger(Hash.sha256(message));
        Element xigema1 = gpk_h;
        Element xigema2 = gpk_h.pow(x.add(y.multiply(m)));
        HashMap<String,Element> xigema = new HashMap<>();
        xigema.put("xigema1",xigema1);
        xigema.put("xigema2",xigema2);
        return xigema;
    }
    public static boolean verify(HashMap<String,Element> xigema,String message){
        BigInteger m = new BigInteger(Hash.sha256(message));
        Element temp1 = pairing.pairing(xigema.get("xigema1"),gpk_X.mul(gpk_Y.pow(m)));
        Element temp2 = pairing.pairing(xigema.get("xigema2"),gpk_g);
        if (temp1.isEqual(temp2)){
            return true;
        }else {
            return false;
        }
    }

    public static void main(String[] args) {
        SetUp();
        generateGroupKeyPair();
        HashMap<String ,Element> xigema =  sign(gsk_x,gsk_y,"12345");
        System.out.println(verify(xigema,"12345"));

    }
}
